package com.mc.moring.main.fragment

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.mc.moring.BafBase.BAFBaseFragment
import com.mc.moring.R
import com.mc.moring.app.LogUtils
import com.mc.moring.base.HttpCallback
import com.mc.moring.base.SaveZiLiPageTool
import com.mc.moring.bean.AppConfigBean
import com.mc.moring.bean.EvaluationGuideInfo
import com.mc.moring.bean.StationMessageListBean
import com.mc.moring.bean.UnReadBean
import com.mc.moring.bean.ZiLiPageUserDataBean
import com.mc.moring.bean.getWebLinkConfigBean
import com.mc.moring.event.UpdateLoanEvent
import com.mc.moring.event.UpdateUserEvent
import com.mc.moring.information.CapitalInforActivity
import com.mc.moring.information.modle.KycModle
import com.mc.moring.login.LoginActivity
import com.mc.moring.main.MainActivity
import com.mc.moring.main.MsgActivity
import com.mc.moring.main.MyLoanActivity
import com.mc.moring.main.MyTradeActivity
import com.mc.moring.main.SettingActivity
import com.mc.moring.main.UserInfoActivity
import com.mc.moring.main.WebViewActivity
import com.mc.moring.main.modle.MianModle
import com.mc.moring.main.modle.PermisosModle
import com.mc.moring.main.modle.PermisosModle.Companion.instant
import com.mc.moring.main.personal.AboutActivity
import com.mc.moring.main.personal.BankAccountListActivity
import com.mc.moring.util.GlideImageLoadUtils
import com.mc.moring.util.GsonUtils
import com.mc.moring.util.IntentUtils
import com.mc.moring.util.PointMgr
import com.mc.moring.util.SPUtils
import com.mc.moring.util.SharePreUtil
import com.mc.moring.util.StringUtils
import com.mc.moring.util.ToastUtils
import com.mc.moring.widge.MarkDialog
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject


/**
 * user center
 * author: Created by nao on 2019/11/13
 * version: 1.0.0
 */
class PersonalFragment : BAFBaseFragment<MainActivity, PersonalFragment>() {

    var swipeLayout: SmartRefreshLayout? = null
    private val view_msg by lazy { mView!!.findViewById<View>(R.id.view_msg) }
    var personalHeadImage: ImageView? = null
    var ll_logged: LinearLayout? = null
    var btn_ace: TextView? = null
    var btn_mi: TextView? = null
    var btn_pre: TextView? = null
    var btn_pol: TextView? = null
    var btn_set: TextView? = null
    var btn_cor: TextView? = null
    var btn_msg: RelativeLayout? = null
    var ll_is_login: LinearLayout? = null
    var tv_name: TextView? = null
    var tv_mobile: TextView? = null
    var tv_login: TextView? = null
    var ll_transaction_records: LinearLayout? = null
    var ll_loan_history: LinearLayout? = null
    var mianModle: MianModle? = null
    var userDataBean: ZiLiPageUserDataBean? = null
    var urlBean: getWebLinkConfigBean? = null

    private val tv_date by lazy { mView!!.findViewById<TextView>(R.id.tv_date) }
    private val tv_money by lazy { mView!!.findViewById<TextView>(R.id.tv_money) }
    private val ly_money_intr by lazy { mView!!.findViewById<LinearLayout>(R.id.ly_money_intr) }
    private val img_mark by lazy { mView!!.findViewById<ImageView>(R.id.img_mark) }
    private lateinit var fatherActivity: MainActivity

    fun newInstance(index: Int): PersonalFragment {
        LogUtils.logE("personal page")
        PointMgr.sendEvent("cl_prile_open_pen")
        Log.e("PointMgr.INSTANCE.sendEvent", "cl_prile_open_pen")
        val fragment = PersonalFragment()
        val bundle = Bundle()
        bundle.putInt(INDEX, index)
        fragment.arguments = bundle
        return fragment
    }

    override fun onAttach(activity: Activity) {
        super.onAttach(activity)
        fatherActivity = activity as MainActivity
    }

    override fun initLayout() = R.layout.fragment_personal
    override fun onResume() {
        Log.e("----","onResume")
        super.onResume()
        getMsg()
        setHeadImage()
        getUnReadMsg()
    }

    fun getMsg() {
        val jsonString: String = SaveZiLiPageTool(getContextView())
            .getKeyValue("user_info") ?: ""
        if (!TextUtils.isEmpty(jsonString)) {
            val userDataBean1: ZiLiPageUserDataBean =
                Gson().fromJson(jsonString, ZiLiPageUserDataBean::class.java)
            Log.e("jsonString",jsonString);
            ZiLiPageUserDataBean.setInstance(userDataBean1)
            userDataBean = ZiLiPageUserDataBean.getInstance()
            Log.e("===userBean1",GsonUtils.getGson().toJson(userDataBean))
            val map: MutableMap<String, String> = java.util.HashMap()
            map["customerId"] = userDataBean?.customerId.toString()
            map["pageIndex"] = "1"
            map["pageSize"] = "20"
            fatherActivity.showMyLoading()
            instant.getStationMessageList(map, object : HttpCallback {
                override fun onSuccess(data: String) {
                    LogUtils.logE("msg list>$data")
                    val bean = Gson().fromJson(
                        data,
                        StationMessageListBean::class.java
                    )
                    if ( bean != null ){
                        activity?.runOnUiThread(Runnable {
                            if (bean.code == "0000") {
                            }
                        })
                    }
                    fatherActivity.hideMyLoading()
                }

                override fun onFaill(e: String) {
                    LogUtils.logE("msg fail>$e")
                    fatherActivity.hideMyLoading()
                }
            })
        }
    }
    fun setHeadImage(){
//        if ( userDataBean?.token!=null ){
//            if (TextUtils.isEmpty(userDataBean?.token)) {
//                personalHeadImage?.setBackgroundResource(R.mipmap.ic_header_nologin)
//            }
//        }

        if (userDataBean?.headImg != null) {
            GlideImageLoadUtils.getInstance().displayLocalImage(
                context?.let { Glide.with(it) },
                personalHeadImage, userDataBean?.headImg, null
            )
        }
    }

    fun getUnReadMsg() {
        val jsonString: String = SaveZiLiPageTool(getContextView())
            .getKeyValue("user_info") ?: ""
        if (!TextUtils.isEmpty(jsonString)) {
            val userDataBean1: ZiLiPageUserDataBean =
                Gson().fromJson(jsonString, ZiLiPageUserDataBean::class.java)
            ZiLiPageUserDataBean.setInstance(userDataBean1)
            userDataBean = ZiLiPageUserDataBean.getInstance()
            val map: MutableMap<String, String> = java.util.HashMap()
            map["customerId"] = userDataBean?.customerId.toString()
            fatherActivity.showMyLoading()
            Log.e("----catch","")
            PermisosModle.instant.getUnreadMessageCount(map, object : HttpCallback {
                override fun onSuccess(data: String) {
                    LogUtils.logE("unread msg：>$data")
                    val bean = Gson().fromJson(
                        data,
                        UnReadBean::class.java
                    )
                    activity?.runOnUiThread(Runnable {
                        if (bean.code == "0000") {
                            LogUtils.logE("unread msg：>${bean.data.unread}")
                            if (bean.data.unread > 0) {
                                view_msg?.visibility = View.VISIBLE
                            } else {
                                view_msg?.visibility = View.GONE
                            }
                        }
                    })
                    fatherActivity.hideMyLoading()
                }

                override fun onFaill(e: String) {
                    LogUtils.logE("unread msg fail>$e")
                    fatherActivity.hideMyLoading()
                }
            })
        }
    }

    override fun afterInjectView(savedInstanceState: Bundle?) {
        Log.e("----","aftetInjectView")
        EventBus.getDefault().register(this)
        if (!TextUtils.isEmpty(SharePreUtil.getStringData("_getWebLinkConfig"))) {
            urlBean = Gson().fromJson(
                SharePreUtil.getStringData("_getWebLinkConfig"),
                getWebLinkConfigBean::class.java
            )
        }
        initEvent()
        personalHeadImage = mView?.findViewById(R.id.personal_head_image)
        swipeLayout = mView?.findViewById(R.id.swipeLayout)
        btn_ace = mView?.findViewById(R.id.btn_ace)
        btn_mi = mView?.findViewById(R.id.btn_mi)
        btn_pre = mView?.findViewById(R.id.btn_pre)
        btn_pol = mView?.findViewById(R.id.btn_pol)
        btn_set = mView?.findViewById(R.id.btn_set)
        btn_cor = mView?.findViewById(R.id.btn_cor)
        btn_msg = mView?.findViewById(R.id.btn_msg)
        ll_is_login = mView?.findViewById(R.id.ll_is_login)
        tv_name = mView?.findViewById(R.id.tv_name)
        tv_mobile = mView?.findViewById(R.id.tv_mobile)
        tv_login = mView?.findViewById(R.id.tv_login)
        ll_logged = mView?.findViewById(R.id.ll_logged)
        ll_transaction_records = mView?.findViewById(R.id.ll_transaction_records)
        ll_loan_history = mView?.findViewById(R.id.ll_loan_history)
        getUserInfo()
//        showEvaluationGuide()
        swipeLayout?.setEnableLoadMore(false)
        swipeLayout?.setOnRefreshListener(OnRefreshListener {
            swipeLayout?.finishRefresh()
            val params: MutableMap<String, String> = HashMap()
            params["name"] = userDataBean?.name.toString()
            params["custId"] = userDataBean?.customerId.toString()
            fatherActivity.showMyLoading()
            mianModle?.getUserInfo(params, object : HttpCallback {
                override fun onSuccess(data: String) {
                    activity?.runOnUiThread(Runnable {
                        LogUtils.logE("user info success>" + data)
                        getUserInfo()
                        getUnReadMsg()
                    })
                    fatherActivity.hideMyLoading()
                }

                override fun onFaill(e: String) {
                    LogUtils.logE("user info fail>" + e)
                    fatherActivity.hideMyLoading()
                }
            })
        })
        ll_logged?.setOnClickListener {
            PointMgr.sendEvent("cl_person_infoof-4_open")
            Log.e("PointMgr.INSTANCE.sendEvent", "cl_person_infoof-4_open")
            if (!TextUtils.isEmpty(userDataBean?.token)) {
                if (TextUtils.equals(userDataBean?.rewrite, "Y")) {
                    val intent = Intent(context, CapitalInforActivity::class.java)
                    startActivity(intent)
                } else {
                    val intent = Intent(context, UserInfoActivity::class.java)
                    startActivity(intent)
                }
            } else {
                ToastUtils.showLong(activity, "Inicio de sesión no funciona por favor volver a iniciar sesión")
                val intent = Intent(context, LoginActivity::class.java)
                startActivity(intent)
            }
        }
        btn_ace?.setOnClickListener {
            PointMgr.sendEvent("cl_person_infoof-11_open")
            Log.e("PointMgr.INSTANCE.sendEvent", "cl_person_infoof-11_open")
            if (!TextUtils.isEmpty(userDataBean?.token)) {
                val intent = Intent(context, AboutActivity::class.java)
                startActivity(intent)
            } else {
                ToastUtils.showLong(activity, "Inicio de sesión no funciona por favor volver a iniciar sesión")
                val intent = Intent(context, LoginActivity::class.java)
                startActivity(intent)
            }
        }
        btn_mi?.setOnClickListener {
            PointMgr.sendEvent("cl_person_infoof-22_open")
            Log.e("PointMgr.INSTANCE.sendEvent", "cl_person_infoof-22_open")
            if (!TextUtils.isEmpty(userDataBean?.token)) {
                if (TextUtils.equals(userDataBean?.rewrite, "Y")) {
                    val intent = Intent(context, CapitalInforActivity::class.java)
                    startActivity(intent)
                } else {
                    val intent = Intent(context, BankAccountListActivity::class.java)
                    startActivity(intent)
                }
            } else {
                ToastUtils.showLong(activity, "Inicio de sesión no funciona por favor volver a iniciar sesión")
                val intent = Intent(context, LoginActivity::class.java)
                startActivity(intent)
            }
        }
        btn_pre?.setOnClickListener {
            PointMgr.sendEvent("cl_person_infoof-13_open")
            Log.e("PointMgr.INSTANCE.sendEvent", "cl_person_infoof-13_open")
            if (!TextUtils.isEmpty(userDataBean?.token)) {
                var intent = Intent(activity, WebViewActivity::class.java)
                intent.putExtra("url", urlBean?.data?.urlFaq)
                startActivity(intent)
            } else {
                ToastUtils.showLong(activity, "Inicio de sesión no funciona por favor volver a iniciar sesión")
                val intent = Intent(context, LoginActivity::class.java)
                startActivity(intent)
            }
        }
        btn_set?.setOnClickListener {
            PointMgr.sendEvent("cl_person_infoof-12_open")
            Log.e("PointMgr.INSTANCE.sendEvent", "cl_person_infoof-12_open")
            if (!TextUtils.isEmpty(userDataBean?.token)) {
                val intent = Intent(context, SettingActivity::class.java)
                startActivity(intent)
            } else {
                ToastUtils.showLong(activity, "Inicio de sesión no funciona por favor volver a iniciar sesión")
                val intent = Intent(context, LoginActivity::class.java)
                startActivity(intent)
            }
        }
        btn_cor?.setOnClickListener {
            if (!TextUtils.isEmpty(userDataBean?.token)) {
                mianModle = MianModle.instant
                var params: HashMap<String, String> = HashMap()
                fatherActivity.showMyLoading()
                mianModle?.securitygetApplicationConfig(params, object : HttpCallback {
                    override fun onSuccess(data: String) {
                        println("")
                        var appConfigBean: AppConfigBean =
                            GsonUtils.getGson().fromJson(data, AppConfigBean::class.java);
                        Log.e("----personalData",data)
                        if (appConfigBean != null) {
                            IntentUtils.openMail(activity, appConfigBean.data.contactEmail)
                        }
                        fatherActivity.hideMyLoading()
                    }

                    override fun onFaill(e: String) {
                        fatherActivity.hideMyLoading()
                    }

                })
            } else {
                ToastUtils.showLong(activity, "Inicio de sesión no funciona por favor volver a iniciar sesión")
                val intent = Intent(context, LoginActivity::class.java)
                startActivity(intent)
            }
        }
        btn_pol?.setOnClickListener {
            if (!TextUtils.isEmpty(userDataBean?.token)) {
                var intent = Intent(activity, WebViewActivity::class.java)
                intent.putExtra("type", "privacyAgree")
                intent.putExtra("url", urlBean?.data?.privacyAgree)
                startActivity(intent)
            } else {
                ToastUtils.showLong(activity, "Inicio de sesión no funciona por favor volver a iniciar sesión")
                val intent = Intent(context, LoginActivity::class.java)
                startActivity(intent)
            }
        }
        btn_msg?.setOnClickListener {
            PointMgr.sendEvent("cl_person_infoof-25_open")
            Log.e("PointMgr.INSTANCE.sendEvent", "cl_person_infoof-25_open")
            if (!TextUtils.isEmpty(userDataBean?.token)) {
                val intent = Intent(context, MsgActivity::class.java)
                startActivity(intent)
            } else {
                ToastUtils.showLong(activity, "Inicio de sesión no funciona por favor volver a iniciar sesión")
                val intent = Intent(context, LoginActivity::class.java)
                startActivity(intent)
            }

        }
        ll_transaction_records?.setOnClickListener {
            if (!TextUtils.isEmpty(userDataBean?.token)) {

                val intent = Intent(context, MyTradeActivity::class.java)
                startActivity(intent)
            } else {
                ToastUtils.showLong(activity, "Inicio de sesión no funciona por favor volver a iniciar sesión")
                val intent = Intent(context, LoginActivity::class.java)
                startActivity(intent)
            }
        }

        ll_loan_history?.setOnClickListener {
            PointMgr.sendEvent("cl_person_infoof-5_open")
            Log.e("PointMgr.INSTANCE.sendEvent", "cl_person_infoof-5_open")
            if (!TextUtils.isEmpty(userDataBean?.token)) {
                val intent = Intent(context, MyLoanActivity::class.java)
                startActivity(intent)
            } else {
                ToastUtils.showLong(activity, "Inicio de sesión no funciona por favor volver a iniciar sesión")
                val intent = Intent(context, LoginActivity::class.java)
                startActivity(intent)
            }
        }


        img_mark.setOnClickListener {
            showMark()
        }


    }

    private fun initEvent() {

    }

    override fun lazyLoad() {
        Log.e("----","lazyLoad")
        mianModle = MianModle.instant
        showEvaluationGuide()
    }

    private fun getUserInfo() {
        try {
            val params: MutableMap<String, String> = java.util.HashMap()
            params["custId"] = ZiLiPageUserDataBean.getInstance().customerId
            fatherActivity.showMyLoading()
            KycModle().getZiLiPageUserFullInfo(params, object : HttpCallback {
                override fun onSuccess(data: String) {
                    requireActivity().runOnUiThread {
                        try {
                            val jsonObject = JSONObject(data)
                            LogUtils.logE("user info>$jsonObject")
                            if (KycModle().isSuccess(jsonObject)) {
                                val dataJSONObject = jsonObject.optJSONObject("data")
                                if (dataJSONObject != null) {
                                    ll_is_login?.visibility = View.VISIBLE
                                    tv_login?.visibility = View.GONE
                                    tv_mobile?.text = StringUtils.keepLastFourDigits(dataJSONObject.optString("mobile"))
                                    SPUtils.setPhone(dataJSONObject.optString("mobile"))
                                    if (TextUtils.isEmpty(dataJSONObject.optString("firstName")) || dataJSONObject.optString("firstName") == "null") {
                                        tv_name?.text = "Halo"
                                    } else {
                                        tv_name?.text =
                                            "Halo，" + dataJSONObject.optString("firstName")
                                    }
                                } else {
                                    ll_is_login?.visibility = View.GONE
                                    tv_login?.visibility = View.VISIBLE
                                }
                            }
                        } catch (e: java.lang.Exception) {
                            e.printStackTrace()
                        }
                    }
                    fatherActivity.hideMyLoading()
                }

                override fun onFaill(e: String) {
                    fatherActivity.hideMyLoading()
                }
            })
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: UpdateLoanEvent) {
        if (event.dataBean == null) {
            ly_money_intr.visibility = View.GONE
        } else {
            ly_money_intr.visibility = View.VISIBLE
            tv_date.setText("${event.dataBean.dueDate}")
            // TimeUtils.date2FormatDate()
            tv_money.setText("${event.dataBean.applyAmount.toString()}")

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: UpdateUserEvent) {
        userDataBean = ZiLiPageUserDataBean.getInstance()
        getUserInfo()
        LogUtils.logE("refresh user info success>>>>" + GsonUtils.getGson().toJson(userDataBean))
    }

    override fun onPause() {
        super.onPause()
        fatherActivity.hideMyLoading()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    var markDialog: MarkDialog? = null
    private fun showMark(){
        if (markDialog != null){
            if (markDialog!!.isShowing){
                return;
            }
        }
        markDialog = MarkDialog(requireActivity())
        markDialog?.show()
    }

    fun showEvaluationGuide() {
        var params: HashMap<String, String> = HashMap()
        fatherActivity.showMyLoading()
        mianModle?.loanSecurityevaluationGuide(params, object : HttpCallback{
            override fun onSuccess(data: String) {
                LogUtils.logE("---loanSecurityevaluationGuide data:$data")
                requireActivity().runOnUiThread{
                    val bean = Gson().fromJson(data, EvaluationGuideInfo::class.java)
                    if (bean.code.equals("0000")) {
                        if (bean.data.open) {
                            img_mark.visibility = View.VISIBLE
                        } else {
                            img_mark.visibility = View.GONE
                        }
                    } else {
                        img_mark.visibility = View.GONE
                    }
                }
                fatherActivity.hideMyLoading()
            }

            override fun onFaill(e: String) {
                fatherActivity.hideMyLoading()
            }

        })
    }

}